<?php

namespace app\api\controller;

use app\admin\model\CouponCodeGoods;
use app\admin\model\Order;
use app\common\model\User;
use app\admin\model\Third;
use app\api\library\ExceptionHandle;
use app\api\library\SendSms;
use app\api\library\Wechat;
use app\common\controller\Api;
use app\common\library\Sms;
use think\Config;
use think\Db;
use think\Validate;
use GuzzleHttp\Exception\RequestException;
use WechatPay\GuzzleMiddleware\WechatPayMiddleware;
use WechatPay\GuzzleMiddleware\Util\PemUtil;
use app\admin\model\WhiteList;
use app\admin\model\CouponCodeClass;

class Coupon extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['notify', 'allCoupon'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\CouponTo();
    }
    /**
     * 下单
     */
    public function order()
    {
        $userid = $this->auth->id;
        $goods_id = $this->request->post('goods_id');
//        $money = $this->request->request('money');
        if (!$goods_id) {
            $this->error('商品id不能为空');
        }

        $res = ExceptionHandle::order($userid, $goods_id);
        if ($res) {
            $this->success('下单成功', $res);
        }
        $this->error('下单失败');
    }

    /**
     * 微信统一支付
     */
    public function pay()
    {
        $order_no = $this->request->post('order_no');
        if (!$order_no) {
            $this->error('订单号不能为空');
        }
        $order = Order::where('order_no', $order_no)->find();
        if (!$order) {
            $this->error('订单不存在');
        }
        $user = User::where(['id' => $this->auth->id])->find();
        if ($user['id'] != $this->auth->id) {
            $this->error('当前订单不属于当前用户');
        }
        $openid = Third::where(['user_id' => $user['id']])->value('openid');
        if(!$openid) {
            $this->error('openid 为空不能进行支付');
        }
        if ($order['status'] !=1) {
            $this->error('订单不能进行支付');
        }
        $white = $this->whiteList($order['user_mobile']);
        if ($white != 1) {
            //通知地址  确保外网能正常访问
            $notify_url = 'https://'.$_SERVER['HTTP_HOST'].'/index.php/api/Coupon/notify';
            //统一下单接口
            $ExceptionHandle = new ExceptionHandle();
            $unifiedorder = $ExceptionHandle->unifiedorder($openid,$order_no,$order->pay_money,$notify_url,'鑫互助权益订单');
            if ($unifiedorder['result_code'] == 'FAIL') {
                $this->error($unifiedorder['err_code_des']);
            }
            $wx_config = Config::get('wx_config');
            $parameters = array(
                'appId' => $wx_config['appid'], //小程序 ID
                'timeStamp' => '' . time() . '', //时间戳
                'nonceStr' => $ExceptionHandle->createNoncestr(), //随机串
                'package' => 'prepay_id=' . $unifiedorder['prepay_id'], //数据包
                'signType' => 'MD5'//签名方式
            );
            //签名
            $parameters['paySign'] = $ExceptionHandle->getWxSign($parameters,$wx_config['mch_key']);
            $parameters['order_no'] = $order_no;
            $this->success('获取成功', $parameters);
        } else {
            $res = ExceptionHandle::NotifyUrlStatus($order_no, $openid);
            if ($res) {
                $this->success('支付成功');
            }
            $this->error('支付失败');
        }
    }

    /**
     * 支付回调
     */
    public  function notify()
    {
        $xml = file_get_contents("php://input");
        file_put_contents('wx.txt', $xml);
        $objectxml = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);//将文件转换成 对象
        $xmljson= json_encode($objectxml);//将对象转换个JSON
        $xmlarray=json_decode($xmljson,true);//将json转换成数组
        $out_trade_no = $xmlarray['out_trade_no'];
        $openid = $xmlarray['openid'];
        ExceptionHandle::NotifyUrlStatus($out_trade_no, $openid);
        $str='<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        echo $str;
		// $out_trade_no = '202205261650200000391081';
		// ExceptionHandle::NotifyUrlStatus($out_trade_no);
    }
    /**
     * 获取签名
     * @url    (授权地址)
     */
    public function GetSign()
    {
        $url = $this->request->request('url');
        $rest = Wechat::getSignPackage($url);
        $this->success(__('success'), $rest);
    }
    /*
    * 白名单
    *
    */
    public function whiteList($mobile)
    {
        $res = false;
        $all = WhiteList::where(['status' => 1])->select();
        if ($all) {
            foreach ($all as $key => &$val){
                if ($val['end_time']) {
                    if (time() > $val['end_time']) {
                        WhiteList::where(['status' => 1])->update(['status' => 2]);
                    }
                }
            }
        }
        $white = WhiteList::where(['mobile' => $mobile, 'status' => 1])->find();
        if ($white && $white->cishu > 0) {
            $res = true;
        }
        return $res;
    }
}